package org.sith.taskrunner.filters.filters;

import org.sith.taskrunner.api.user.User;
import org.sith.taskrunner.ejb.UserThreadKeeper;
import org.sith.taskrunner.ejb.services.UserManagerService;

import javax.ejb.EJB;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class AutorizationFilter implements Filter {
    private static final String USER_ATTR_NAME = "user";
    private static final String LOGIN_ATTR_NAME = "login";
    private static final String PASS_ATTR_NAME = "pass";

    @EJB(name = "UserManagerServiceEJB")
    private UserManagerService userManagerService;

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp,
                         FilterChain chain) throws ServletException, IOException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpSession session = request.getSession();
        String contextPath = session.getServletContext().getContextPath();
        User user = (User) session.getAttribute(USER_ATTR_NAME);
        if (user != null) {
            chain.doFilter(req, resp);
            return;
        }
        String login = request.getParameter(LOGIN_ATTR_NAME);
        String pass = request.getParameter(PASS_ATTR_NAME);
        if (login == null || login.isEmpty()) {
            response.sendRedirect(contextPath + "/login.jsp");
            return;
        }
        user = userManagerService.getUserByNameAndPassword(login, pass);
        if (user != null) {
            request.getSession().setAttribute(USER_ATTR_NAME, user);
            UserThreadKeeper.setThreadUser(user);
            chain.doFilter(req, resp);
        } else {
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("/login.jsp");
            request.setAttribute("errorMessage", "The username or password you entered is incorrect.");
            requestDispatcher.forward(request, response);
        }

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {        
    }
}
